<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Data Bunker - user profile</title>
    <script src="conf.js"></script>
    <script src="site.js"></script>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">

    <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap.bundle.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/7.0.4/jsoneditor.min.css" rel="stylesheet"
        type="text/css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/7.0.4/jsoneditor.min.js"></script>
<script>
conf = loadUIConfiguration();
if (conf["custom_css_link"]) {
  document.write("<link rel='stylesheet' type='text/css' href='" + conf["custom_css_link"] +"' />");
}
</script>
</head>

<body>
    <div class="container">
        <div class="row col-md-12">
            <div style="width:100%;">
                <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                    <button class="navbar-toggler" type="button" data-toggle="collapse"
                        data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false"
                        aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
                        <ul class="navbar-nav">
				<script>showUserMenu();</script>
                        </ul>
                    </div>
                </nav>
            </div>
            <div class="bigblock">
                <div class="row">
                    <div class="col-9 col-md-9">
                        <h4>My profile data</h4>
                    </div>
                    <div class="col-3 col-md3 text-right">
                        <button onclick="return forgetme();" class="btn btn-warning">Forget me</button>
                    </div>
                </div>
                <p id="msg">Click on a field to edit. When done click on "Save".</p>
		<div id='status-message'></div>
                <div id="jsoneditor" style="width:100%;height:300px;overflow:auto;"></div>
                <pre id="data"></pre>

                <div class="form-group">
                    <div class="peers ai-c jc-sb fxw-nw">
                        <div class="peer">
                            <!--
                            <div class="checkbox checkbox-circle checkbox-info peers ai-c">
                                <input type="checkbox" id="inputCall1" name="inputCheckboxesCall" class="peer">
                                <label for="inputCall1" class="peers peer-greed js-sb ai-c">
                                    <span class="peer peer-greed">Remember Me</span></label></div>
                                -->
                        </div>
                        <div class="peer">
                            <button onclick="return savebtn();" class="btn btn-primary">Save</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
	    <script>displayFooterLinks();</script>
    </div>
    <script>
        var xtoken = window.localStorage.getItem('xtoken');
        var token = window.localStorage.getItem('token');
        var ttype = window.localStorage.getItem('type');
        var pKeys = ["password", "pwd", "pass", "parol", "passwd"];
        var editor;
        function forgetme() {
            var heading = "Confirm action";
            var question = "Are you sure? This operation can not be undone.";
            var cancelButtonTxt = "Close popup";
            var okButtonTxt = "Forget me!";
            var confirmModal =
                $('<div class="modal fade" role="dialog"><div class="modal-dialog" role="document"><div class="modal-content">' +
                    '<div class="modal-header">' +
                    '<h5 class="modal-title">' + heading + '</h5>' +
                    '<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
                    '<span aria-hidden="true">&times;</span></button>' +
                    '</div>' +
                    '<div class="modal-body">' +
                    '<p>' + question + '</p>' +
                    '</div>' +
                    '<div class="modal-footer">' +
                    '<a href="#" class="btn" data-dismiss="modal">' +
                    cancelButtonTxt +
                    '</a>' +
                    '<a href="#" id="okButton" class="btn btn-warning">' +
                    okButtonTxt +
                    '</a>' +
                    '</div>' +
                    '</div></div></div>');

            confirmModal.find('#okButton').click(function (event) {
                //callback();
                forgetMeDo();
                confirmModal.modal('hide');
            });
            confirmModal.modal('show');
        }
        function forgetMeDo(brief) {
            var xhr = new XMLHttpRequest();
            xhr.open('DELETE', "/v1/user/token/" + token);
            xhr.setRequestHeader("X-Bunker-Token", xtoken)
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var data = JSON.parse(xhr.responseText);
                    if (data.status == "ok" && data.result && data.result == "request-created") {
                        showAlert("Admin request created to remove your account.");
                    } else if (data.status == "ok" && data.result && data.result == "request-exists") {
                        showAlert("Similar request already exists for Admin approval.");
                    } else {
                        bunker_logout();
                    }
                } else if (xhr.status > 400 && xhr.status < 500) {
                    document.location = "/";
                }
            }
            xhr.send();
        }
        function savebtn() {
            const updatedJson = editor.get()
            var params = JSON.stringify(updatedJson);
            //alert(d);
            var xhr0 = new XMLHttpRequest();
            // first save consent
            xhr0.open('PUT', "/v1/user/token/" + token);
            xhr0.setRequestHeader("X-Bunker-Token", xtoken)
            xhr0.setRequestHeader('Content-type', 'application/json');
            xhr0.onload = function () {
                if (xhr0.status === 200) {
                    var data = JSON.parse(xhr0.responseText);
                    if (data.status == "ok" && data.result && data.result == "request-created") {
                        showAlert("Admin request created to approve changes in your profile.");
                    } else if (data.status == "ok" && data.result && data.result == "request-exists") {
                        showAlert("Similar request already exists for Admin approval.");
		    } else {
			showSuccess('Record saved.');
		    }
                } else if (xhr0.status === 403) {
                    document.location = "/";
                } else {
                    var data = JSON.parse(xhr0.responseText);
                    if (data.status == "error") {
			showError("Failed to save. "+data.message);
                    }
                }
            }
            xhr0.send(params);
        }
        $('#msg').val("Display: " + ttype + " " + token);
        /*
        $.get("/v1/token/" + token, function (data) {
        }, "json");
        */
        var xhr = new XMLHttpRequest();
        xhr.open('GET', '/v1/user/token/' + token);
        xhr.setRequestHeader("X-Bunker-Token", xtoken)
        xhr.setRequestHeader('Content-type', 'application/json');
        xhr.onload = function () {
            if (xhr.status === 200) {
                var data = JSON.parse(xhr.responseText);
                if (data.status == "ok") {
                    //$('#msg').text("Access xtoken value: " + xtoken + " user: " + token)
                    // create the editor
                    const container = document.getElementById("jsoneditor")
                    const options = {
                        "mode": "form",
                        "statusBar": false,
                        "mainMenuBar": false,
                        "navigationBar": false,
                    }
                    editor = new JSONEditor(container, options)
                    // remove password field from displaying to user
                    for (var key in data.data) {
                        var k0 = key.toLowerCase();
                        if (pKeys.includes(k0)) {
                            delete data.data[key];
                        }
                    }
                    editor.set(data.data)

                    // get json
                    //const updatedJson = editor.get()
                    /*
                    var d = JSON.stringify(data.data, null, 4);
                    $('#data').append('<code class="json">' + d + '</code>');
                    document.querySelectorAll('pre code').forEach((block) => {
                        hljs.highlightBlock(block);
                    });
                    */
                }
            } else if (xhr.status > 400 && xhr.status < 500) {
                document.location = "/";
            }
        }
        xhr.send();
    </script>

</body>
